import { plugin, Messagetype } from 'alemon'
import nsfwjsApi from 'nsfwjs-api'
import { join } from 'node:path'
import { MyDirPath } from '../app.config.js'
export class nY_picture extends plugin {
  constructor() {
    super({
      dsc: '禁图',
      priority: 2,
      rule: [
        {
          reg: /(.*)/,
          fnc: 'ny'
        }
      ]
    })
    // 是否使用本地模型 默认false
    nsfwjsApi.UseModel = true

    // 模型位置 默认运行文件夹下model, UseModel为false时无效
    nsfwjsApi.model = join(MyDirPath, '/resources/model/')

    //   copy模型文件夹, UseModel为false时无效
    // 模型文件 https://github.com/infinitered/nsfwjs/tree/master/example/nsfw_demo/public/model
    nsfwjsApi.cpModel()

    // gif配置
    nsfwjsApi.gif = {
      fps: 1, //每秒帧数，从中按比例选取帧（默认为所有帧）
      topk: 1 // 每帧返回的结果数（默认全部为 5）
    }
  }
  async ny(e: Messagetype): Promise<boolean> {
    //    需要私域或公域事件
    if (e.eventType !== 'CREATE' && e.event !== 'MESSAGES' && !e.isGroup) {
      return
    }

    if (e.msg.attachments) {
      const imgList = e.msg.attachments

      try {
        imgList.forEach(async item => {
          const result = await nsfwjsApi
            .identificationOfPictures('https://' + item.url)
            .catch(err => err)

          // 成功
          if (result.code === 200) {
            let msg: {
              className: 'Neutral' | 'Drawing' | 'Porn' | 'Hentai' | 'Sexy'
              probability: number
            }
            if (result.msg[0] instanceof Array) {
              msg = result.msg[0][0]
            } else {
              msg = result.msg[0]
            }
            // console.log(msg)

            if (
              ['Porn', 'Hentai', 'Sexy'].includes(msg.className) &&
              //  概率
              msg.probability >= 0.6
            ) {
              //  撤回消息
              client.messageApi
                .deleteMessage(e.msg.channel_id, e.msg.id, false)
                .then(() => {
                  // 禁言
                  client.muteApi
                    .muteMember(e.msg.guild_id, e.msg.author.id, {
                      seconds: 10 * 60 + '' // 10分钟
                    })
                    .then(async () => {
                      return e.reply(`<@!${e.msg.author.id}> 请文明发图`)
                    })
                })
                .catch(async () => {
                  return e.reply(`<@!${e.msg.author.id}> 虽然禁不了你，但请文明发图`)
                })
            }
          }
        })
      } catch (error) {
        console.log(error)
      }
    }
  }
}
